<template>
    <el-dialog :title="title" :visible.sync="dialogForm" width="800px">
        <el-form :inline="true" :model="form" ref="form" v-loading="loading" class="search-form" :rules="rules"
                 label-width="120px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="计费规则名称：" prop="feeRuleName">
                        <el-input v-model="form.feeRuleName"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属单位：">
                        <el-input v-model="form.orgName" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="业务模式：" prop="businessModule">
                        <el-select v-model="form.businessModule" @change="handleChangeModule" placeholder="请选择"
                                   clearable>
                            <el-option v-for="[key, val] in _dictBusinessModule" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="计费标准：">
                        基本标准
                    </el-form-item>
                </el-col>
            </el-row>
            <!--<el-row>-->
                <!--<el-col :span="12">-->
                    <!--<el-form-item label="计费时间起">-->
                        <!--<el-date-picker v-model="form.ruleBeginDate"-->
                                        <!--type="date"-->
                                        <!--format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>-->
                    <!--</el-form-item>-->
                <!--</el-col>-->
                <!--<el-col :span="12">-->
                    <!--<el-form-item label="计费时间止">-->
                        <!--<el-date-picker v-model="form.ruleEndDate"-->
                                        <!--type="date"-->
                                        <!--format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>-->
                    <!--</el-form-item>-->
                <!--</el-col>-->
            <!--</el-row>-->

            <el-row>
                <el-col :span="12">
                    <el-form-item label="计费指标：" prop="feeUnit">
                        <el-select v-model="form.feeUnit" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictFeeUnit" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="开票税率：" prop="rate">
                        <el-input v-model="form.rate"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="4" style="margin-right: -6px;">
                    <el-form-item label="计费时间:">
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <date-slot :startDate.sync="form.ruleBeginDate" :endDate.sync="form.ruleEndDate"></date-slot>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="计费条件：" prop="feeRule">
                        <div v-for="(item,index) in form.feeRule" :key="index">
                            <el-select v-model="item.code" style="width: 120px"
                                       :disabled="!form.businessModule"
                                       @change="v=>handleChangeRule(v,item,index)"
                                       placeholder="请选择" clearable>
                                <el-option v-for="rule in ruleList" :key="rule.code" :label="rule.name"
                                           :value="rule.code">
                                </el-option>
                            </el-select>
                            <el-select v-model="item.operator" @change="handleChangeOp(item,index)" style="width: 120px"
                                       placeholder="请选择" clearable>
                                <el-option v-for="[key, val] in _dictRuleOperator" :key="key" :label="val" :value="key">
                                </el-option>
                            </el-select>

                            <!--<el-tooltip v-if="item.ruleDataType!=='TEXT'&&isClick"-->
                            <!--:disabled="item.operator!=='in'&&item.operator!=='nIn'"-->
                            <!--class="item" effect="dark" :content="getContent(item)" placement="top">-->
                            <el-select v-model="item.typeValue"
                                       v-if="item.ruleDataType!=='TEXT'&&isClick"
                                       @focus="handleChangeCode(item)"
                                       placeholder="请选择"
                                       :multiple="item.operator==='in'||item.operator==='nIn'"
                                       :collapse-tags="item.operator==='in'||item.operator==='nIn'"
                                       :disabled="!item.code"
                                       clearable>
                                <el-option v-for="rule in item.list" :key="rule.code" :label="rule.name"
                                           :value="rule.code">
                                </el-option>
                            </el-select>
                            <!--</el-tooltip>-->

                            <el-input style="width: 188px" v-if="item.ruleDataType==='TEXT'"
                                      v-model="item.typeValue"></el-input>


                            <el-select v-model="item.isExistSub" style="width: 120px" placeholder="请选择" clearable>
                                <el-option v-for="[key, val] in _dictRuleConnect" :key="key" :label="val" :value="key">
                                </el-option>
                            </el-select>
                            <el-button v-if="index===form.feeRule.length-1"
                                       @click="form.feeRule.push({ code: '', operator: '', typeValue: '', dataSource: [], list:[],ruleDataType: '',isExistSub:'AND' })"
                                       type="text" icon="el-icon-plus" size="medium"></el-button>
                            <el-button v-if="index!==form.feeRule.length&&form.feeRule.length>1"
                                       @click="form.feeRule.splice(index,1)"
                                       type="text" icon="el-icon-close" style="color: red" size="medium"></el-button>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="计费规则描述：">
                        <el-input type="textarea" :rows="3" style="width: 570px" :maxLength="255" placeholder="请输入内容"
                                  v-model="form.feeRuleDesc"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="费率影响因素：">
                        <div v-for="(item,index) in form.rateFactor">
                            <el-select v-model="item.code" @change="handleChangeRate(item)" placeholder="请选择" clearable>
                                <el-option v-for="rule in ruleList" :key="rule.code" :label="rule.name"
                                           :value="rule.code">
                                </el-option>
                            </el-select>
                            <el-button v-if="index===form.rateFactor.length-1"
                                       @click="form.rateFactor.push({ code:'',name:'' })"
                                       type="text" icon="el-icon-plus" size="medium"></el-button>
                            <el-button v-if="index!==form.rateFactor.length&&form.rateFactor.length>1"
                                       @click="form.rateFactor.splice(index,1)"
                                       type="text" icon="el-icon-close" style="color: red" size="medium"></el-button>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogForm = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit"
                       :loading="$store.getters.loadingBtn">
                确 定
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
    import { getRuleRuleList, getRuleCodeValue, addRuleList, editRuleList } from "@/api/balance/balance";
    import { maxLength, normalLength } from "@/utils/rules";
    import { PUBLIC_NUMBER_NULL } from "@/utils/Reg";
    import { variableSearch } from "@/api/balance/balance";
    import dateSlot from '@/components/date/dateSlot';

    export default {
        name: "ruleForm",
        components: {
            dateSlot
        },
        // props:['ruleType'],
        // props: {
        //     ruleType: {
        //         type: String,
        //         required: true
        //     }
        // },
        data() {
            return {
                dialogForm: false,
                isEdit: false,
                form: this.clearForm(),
                rules: {
                    feeRuleName: [{ required: true, message: '请输入规则名称', trigger: 'change' }, normalLength],
                    businessModule: [{ required: true, message: '请选择业务模式', trigger: 'change' }],
                    feeUnit: [{ required: true, message: '请选择计费指标', trigger: 'change' }],
                    feeRule: [{ required: true, message: '请选择计费条件', trigger: 'change' }],
                    rate: [{ validator: PUBLIC_NUMBER_NULL, trigger: 'change' }],
                },
                ruleList: [],
                isClick: true,
                lock: true,
                loading: false,
                create: true,
            }
        },
        methods: {
            handleSubmit() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        console.log(this.form)
                        let data = {
                            ...JSON.parse(JSON.stringify(this.form)),
                            ruleType: 'fee'
                        }
                        console.log('data')
                        console.log(data)
                        data.feeRule.map(m => {
                            if (m.operator === 'in' || m.operator === 'nIn') {
                                m.typeValue = m.typeValue.toString()
                            }
                        })
                        this.isEdit ? this.handleEdit(data) : this.handleAdd(data)
                    } else {
                        this.$message({
                            message: '请检查表单',
                            type: 'error'
                        })
                    }
                })

            },
            handleAdd(data) {
                addRuleList(data).then(res => {
                    this.$message({ message: '新增成功!', type: 'success' })
                    this.dialogForm = false
                })
            },
            handleEdit(data) {
                editRuleList(data.id, data).then(res => {
                    this.$message({ message: '编辑成功!', type: 'success' })
                    this.dialogForm = false
                })
            },
            handleChangeRule(val, item, index) {
                console.log(val, item, index)
                if (this.form.feeRule[index].typeValue) {
                    this.form.feeRule[index].typeValue = ''
                }
                this.ruleList.forEach((f, i) => {
                    if (val === f.code) {
                        console.log(this.form.feeRule)
                        this.form.feeRule[index].ruleDataType = f.ruleDataType
                        this.form.feeRule[index].dataSource = f.dataSource
                    }
                })
            },
            handleChangeModule(val) {
                console.log(val)
                let params = {
                    search_EQ_businessModule: val
                }
                getRuleRuleList(params).then(res => {
                    this.ruleList = res.data.aaData
                    if (!this.create) {
                        this.create = false
                        this.form.feeRule.splice(0, this.form.feeRule.length)
                        this.form.feeRule.push({
                            code: '',
                            operator: '',
                            typeValue: '',
                            dataSource: [],
                            list: [],
                            ruleDataType: '',
                            isExistSub: 'AND'
                        })
                    }
                    console.log(this.isEdit, this.lock)
                    if (this.isEdit && this.lock) {
                        this.lock = false
                        // this.getSource(0)
                        this.form.feeRule.forEach(el => {
                            const result = this.ruleList.findIndex(ol => {
                                return el.code === ol.code
                            })
                            if (result !== -1) {
                                el.ruleDataType = this.ruleList[result].ruleDataType
                                el.dataSource = this.ruleList[result].dataSource
                                if (this.ruleList[result].dataSource === 'SELECT') {
                                    variableSearch(this.ruleList[result].dataSource).then(res => {
                                        const data = res.data.aaData
                                        for (let i = 0; i < data.length; i++) {
                                            const fffff = data[i]
                                            el.list.push({
                                                name: fffff[item.code],
                                                code: fffff[item.code],
                                            })
                                        }
                                    })
                                } else if (this.ruleList[result].ruleDataType === 'ARRAY') {
                                    let list = this.ruleList[result].dataSource.split(',')
                                    for (let i = 0; i < list.length; i++) {
                                        const fffff = list[i]
                                        el.list.push({
                                            name: fffff.split('-')[1],
                                            code: fffff.split('-')[0],
                                        })
                                    }
                                } else if (this.ruleList[result].ruleDataType === 'TEXT') {
                                    el.ruleDataType = 'TEXT'
                                }
                            }
                        })

                    }
                })
            },
            // 获取dataSource
            getSource(val) {
                this.loading = true
                if (val < this.form.feeRule.length) {
                    let item = this.form.feeRule[val]
                    this.ruleList.forEach((f, i) => {
                        if (f.code === item.code && f.ruleDataType !== 'TEXT') {
                            item.ruleDataType = f.ruleDataType
                            item.dataSource = f.dataSource
                            if (f.ruleDataType === 'SELECT') {
                                variableSearch(f.dataSource).then(res => {
                                    const data = res.data.aaData
                                    for (let i = 0; i < data.length; i++) {
                                        const el = data[i]
                                        item.list.push({
                                            name: el[item.code],
                                            code: el[item.code],
                                        })
                                    }
                                    this.getSource(val + 1)
                                })
                            } else if (f.ruleDataType === 'ARRAY') {
                                let list = f.dataSource.split(',')
                                for (let i = 0; i < list.length; i++) {
                                    const el = list[i]
                                    item.list.push({
                                        name: el.split('-')[1],
                                        code: el.split('-')[0],
                                    })
                                }
                                this.getSource(val + 1)
                            }
                        } else if (f.ruleDataType === 'TEXT') {
                            item.ruleDataType = 'TEXT'
                            this.getSource(val + 1)
                        } else {
                            this.getSource(val + 1)
                        }
                    })
                } else {
                    this.loading = false
                }
                console.log(111, this.form)
            },
            // 因素改变
            handleChangeCode(item) {
                console.log(item)
                item.list = []
                if (item.ruleDataType === 'SELECT') {
                    variableSearch(item.dataSource).then(res => {
                        const data = res.data.aaData
                        if (item.code === 'shipAgentCode') {
                            for (let i = 0; i < data.length; i++) {
                                const el = data[i]
                                console.log(el)
                                item.list.push({
                                    name: el.shortName,
                                    code: el.customerCode,
                                })
                            }
                        } else {
                            for (let i = 0; i < data.length; i++) {
                                const el = data[i]
                                item.list.push({
                                    name: el[item.code],
                                    code: el[item.code],
                                })
                            }
                        }
                    })
                } else {
                    let list = item.dataSource.split(',')
                    for (let i = 0; i < list.length; i++) {
                        const el = list[i]
                        item.list.push({
                            name: el.split('-')[1],
                            code: el.split('-')[0],
                        })
                    }
                }

            },
            handleChangeOp(item, index) {
                let data = {
                    ...this.form.feeRule[index],
                    typeValue: ''
                }
                this.form.feeRule.splice(index, 1, data)
                console.log(this.form.feeRule)
                if (item.operator === 'in' || item.operator === 'nIn') {
                    this.isClick = false
                    let newData = {
                        ...this.form.feeRule[index],
                        typeValue: []
                    }
                    this.$nextTick(() => {
                        console.log(this.form.feeRule)
                        this.isClick = true
                        this.form.feeRule.splice(index, 1, newData)
                    })
                }
            },
            handleChangeRate(item) {
                this.ruleList.forEach(f => {
                    if (f.code === item.code) {
                        item.name = f.name
                    }
                })
            },
            clearForm() {
                return {
                    feeRuleName: "",
                    orgId: this.$store.getters.currentUser.org.id,
                    orgName: this.$store.getters.currentUser.org.name,
                    businessModule: "",
                    chargingMode: "STANDARD",
                    feeUnit: "",
                    rate: "",
                    feeRuleDesc: "",
                    feeRule: [{           // 计费条件
                        code: "",
                        operator: "",
                        typeValue: '',
                        dataSource: [],
                        list: [],
                        ruleDataType: '',
                        isExistSub: 'AND',
                    }],
                    rateFactor: [{
                        name: "",
                        code: "",
                    }],
                    ruleBeginDate: '',
                    ruleEndDate: ''
                }
            },
            getContent(item) {
                console.log(item)
                let content = []
                if (item.operator === 'in' || item.operator === 'nIn') {
                    for (let i = 0; i < item.typeValue.length; i++) {
                        const el = item.typeValue[i]
                        console.log(el)
                        item.list.forEach(f => {
                            if (el === f.code) {
                                content.push(f.name)
                            }
                        })
                    }
                }
                return content.toString()
            }
        },
        computed: {
            title() {
                let [title, formType] = ['计费规则', '新增']
                if (this.type === 'fee') {
                    title = '计费规则'
                }
                if (this.isEdit) {
                    formType = '编辑'
                }
                return formType + title
            }
        },
        watch: {
            dialogForm(bool) {
                if (!bool) {
                    this.$parent.dialogForm = false
                    this.$emit('load')
                }
            }
        }
    }
</script>

<style scoped>

</style>
